package pr.lanmu.config.mybatis;

import cn.hutool.core.util.ReflectUtil;
import com.mybatisflex.annotation.InsertListener;
import lombok.SneakyThrows;
import org.apache.commons.lang3.reflect.FieldUtils;
import pr.lanmu.config.util.Current;
import pr.lanmu.config.util.Log;

import java.lang.reflect.Field;
import java.util.Optional;

public class MyInsertListener implements InsertListener {
    private static final String STATUS = "status";
    private static final String UPDATE_TIME = "updateTime";
    private static final String UPDATE_USER_ID = "updateUserId";
    private static final String CREATE_TIME = "createTime";
    private static final String CREATE_USER_ID = "createUserId";
    private static final Long SYSTEM = 0L;

    @Override
    @SneakyThrows
    public void onInsert(Object entity) {
        try {
            Long userId = Optional.ofNullable(Current.getUserId()).orElse(SYSTEM);
            Class<?> clazz = entity.getClass();
            long now = System.currentTimeMillis();
            //更新时间
            Field updateTime = ReflectUtil.getField(clazz, UPDATE_TIME);
            FieldUtils.writeField(updateTime, entity, now, true);
            //更新用户
            Field updateUserId = ReflectUtil.getField(clazz, UPDATE_USER_ID);
            FieldUtils.writeField(updateUserId, entity, userId, true);
            //创建时间
            Field createTime = ReflectUtil.getField(clazz, CREATE_TIME);
            FieldUtils.writeField(createTime, entity, now, true);
            //创建用户
            Field createUserId = ReflectUtil.getField(clazz, CREATE_USER_ID);
            FieldUtils.writeField(createUserId, entity, userId, true);
            //状态
            Field status = ReflectUtil.getField(clazz, STATUS);
            FieldUtils.writeField(status, entity, true, true);
        } catch (Exception e) {
            Log.warn("增强插入值属性不存在");
        }
    }
}